<?php
namespace app\operator\controller;
use think\Db;
use think\Validate;
use think\File;
use mlsmt\Cabinet\Send;

use Qcloud\cos\Api;
class Seller extends Common
{
    //添加商铺
    public function addseller()
    {
        
        $data = input('param.');

        $seller = $data['seller'];
        $seller['oid'] = $data['oid'];
        $validate = \think\Loader::validate('Seller'); 

        if(!$validate->scene('add')->check($seller)){
            $res['code'] = 0;
            $res['msg'] =  $validate->getError();
            return $res;
        }
        $openid = mwdecrypt($data['openid']);

        $user = Db::name('operator_users')->where('oid',$data['oid'])->where('openid',$openid)->field('id')->find();


        $seller['shopstart'] = substr($seller['shopstart'],0,2).substr($seller['shopstart'],-2,2);
        $seller['shopend'] = substr($seller['shopend'],0,2).substr($seller['shopend'],-2,2);
        $seller['create_time'] = time();
        $seller['create_user'] =  $user['id'];
        $sid=Db::name('seller')->insertGetId($seller);
        
        if($sid){
            return ['code'=>1,'sid'=>$sid];
        }else{
            return ['code'=>0,'msg'=>'添加失败！！'];
        }
       
    }
    //修改商铺信息
    public function editseller()
    {
        
        $data = input('param.');

        $seller = $data['seller'];
        $seller['oid'] = $data['oid'];
        $validate = \think\Loader::validate('Seller'); 

        if(!$validate->scene('add')->check($seller)){
            $res['code'] = 0;
            $res['msg'] =  $validate->getError();
            return $res;
        }
        $openid = mwdecrypt($data['openid']);

        $seller['shopstart'] = substr($seller['shopstart'],0,2).substr($seller['shopstart'],-2,2);
        $seller['shopend'] = substr($seller['shopend'],0,2).substr($seller['shopend'],-2,2);

        $status=Db::name('seller')->update($seller);
        if($status){
            return ['code'=>1];
        }else{
            return ['code'=>0,'msg'=>'没有修改任何信息！'];
        }
       
    }
    //上传图片
    public function uploadpicture()
    {
        if(request()->file('picture')){
            $file = request()->file('picture');
    
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');

            $file = $info->getSaveName();
            if($file){
                $cosApi = new Api(config('Qcloud'));
                $bucket = config('Qcloud.bucket');
                $src = ROOT_PATH . 'public/uploads/'.$file;
                $dst = 'operator/logo/'. $file;
                $ret = $cosApi->upload($bucket, $src, $dst);

                if($ret['code']==0){
                    $path = $ret['data']['resource_path'];  //获取资源文件路径（包含了APPID和bucketname）
                    $len = strlen($bucket);  //计算bucketname长度
                    $start = strpos($path,$bucket);   //计算bucketname第一次出现的问题
                    $start +=$len;  
                    $newpath = substr($path,$start);  //截取路径
                    unlink($src);  //删除服务器上面的资源文件
                    $res['code'] = '1';
                    $res['picture'] = $newpath;  //资源文件路径（需要前面添加上域名地址才可以使用）
                    $res['url'] = $ret['data']['access_url'];   //资源文件URL
                    return $res;
                }



            }
            
            $res['code'] = '0' ;
            return $res;
            
            
        }else{
            $res['code'] = '0' ;
            return $res;
        }
        
     
    }
    //商家详情
    public function info()
    {
        $id = input('param.id');
        $oid = input('param.oid');
        

        //获取商家详情
        $info = Db::name('seller')
            ->where('id',$id)
            ->field('id,name,area,addr,picture,phone,longitude,latitude,shopstart,shopend,averageprice,contacts,mobile')
            ->find();
        if($info['picture']){
            $info['picture'] = config('resourceurl').$info['picture'];
        }
        
        return $info;

    }
    //附近商家
    public function sellerlist()
    {
        
        $oid = input('param.oid');
        $longitude = input('param.longitude');
        $latitude = input('param.latitude');
        $search = input('param.search');

        
        if($search){
            $list = Db::name('seller')
            ->field('id,name,area,phone,addr,longitude,latitude,shopstart,shopend,averageprice')
            ->where('oid',$oid)
            ->where('status','1')
            ->where('name|addr|phone','like','%'.$search.'%')
            ->where('is_delete',1)
            ->select();
        }else{
            $operator = Db::name('operator')->field('distance')->where('id',$oid)->find();
            isset($operator['distance'])?$distance=$operator['distance']:$distance=5;
            $distance = $distance*0.009;

            $time = (int)(date("Hi"));
            $list = Db::name('seller')
            ->field('id,name,area,addr,phone,longitude,latitude,shopstart,shopend,averageprice')
            ->where('oid',$oid)
            ->where('status','1')
            ->where('`longitude` < '.($longitude+0.01).' AND `longitude` > '.($longitude-0.01))
            ->where('`latitude` < '.($latitude+0.01).' AND `latitude` > '.($latitude-0.01))
            ->where('`shopstart` <= '.$time.' AND `shopend` >= '.$time)
            ->where('is_delete',1)
            ->select();
        }
        
        return $list;

    }

    //库存数量
    public function stock()
    {
        $sid = input('param.sid');
        $oid = input('param.oid');
        $openid = mwdecrypt(input('param.openid'));
        $charecabinet = Db::name('charecabinet')
            ->where('sid',$sid)
            ->where('status',1)
            ->field('id,cabinet_id,devicenum')
            ->where('is_delete',1)
            ->select();

        $info['devicenum'] = 0;
        $info['stock'] = 0;
        foreach ($charecabinet as $key => $value) {
            $Send = new Send($value['cabinet_id']);
            $res = $Send->StockNum();

            if($res['types']==1){
                /*$logdata = array(
                    'oid' => $oid,
                    'mode' => 2,
                    'operation' => 'StockNum',
                    'info' => '',
                    'result' => json_encode($res),
                    'openid'  => $openid,
                );
                $Send->Log($logdata);//记录机柜日志*/
                $info['devicenum'] += $value['devicenum'];
                $info['stock'] += $res['info'];
            }
        }

        $info['surplus'] =$info['devicenum']-$info['stock'];

        return $info;
    }
    //设备详情
    public function deviceinfo()
    {
        $sid = input('param.sid');
        $oid = input('param.oid');
        $charecabinet = Db::name('charecabinet')
            ->where('sid',$sid)
            ->where('status',1)
            ->field('id,cabinet_id')
            ->where('is_delete',1)
            ->select();

        $info['count'] = count($charecabinet);
        if(!$info['count']){
            $info['code'] = 0 ;
        }else{
            $info['code'] = 1;
            $info['charecabinet'] = $charecabinet;
        }
        return $info;
    }
}
